package com.wtp.wallpaper.task;

import com.wtp.wallpaper.annotation.ScheduledAnnotation;
import com.wtp.wallpaper.common.constant.PictureOssPathConstant;
import com.wtp.wallpaper.utils.PictureReduceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;

@Slf4j
@Component
@ScheduledAnnotation(value = "清理过期图片",
        cron = "0 0 0/1 * * ?",
        description = "该定时任务用于清理用户上传到服务器但未产生数据关联的垃圾图片，一小时执行一次")

public class CleanExpirePictureTask implements Runnable{

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    //@Scheduled(fixedRate = 7200000) // 每小时执行一次
    public void cleanExpiredTempFiles(){
        log.info("开始删除垃圾文件");
        // 1. 获取所有Redis中未提交的文件记录
        Set<String> keys = redisTemplate.keys("upload:image:*");
        assert keys != null;
        for (String key : keys) {
            Long uploadTime = (Long) redisTemplate.opsForValue().get(key);
            String fileName = key.replace("upload:image:", "");

            // 2. 检查是否超时（例如2小时）
            if (uploadTime != null && System.currentTimeMillis() - uploadTime > 7200000) {
                // 3. 删除文件
                Path filePath = Paths.get(PictureOssPathConstant.DEFAULT_TEMP, fileName);
                try {
                    Files.deleteIfExists(filePath);
                    // 4. 删除Redis记录
                    redisTemplate.delete(key);
                } catch (IOException e) {
                    log.error("删除文件失败: {}", fileName, e);
                }
            }
        }

        keys = redisTemplate.keys("uploadBatch:*");
        assert keys != null;
        for (String key : keys) {
            Long uploadTime = (Long) redisTemplate.opsForValue().get(key);
            String dir = key.replace("uploadBatch:", "");

            if (uploadTime != null && System.currentTimeMillis() - uploadTime > 7200000) {
                PictureReduceUtil.DeleteFolderContents(Path.of(dir));
                redisTemplate.delete(key);
            }
        }
        log.info("删除垃圾文件完成");
    }

    @Override
    public void run() {
        cleanExpiredTempFiles();
    }
}
